import { ElMessage } from 'element-plus'
import { computed, reactive, ref, toRefs } from 'vue'

export interface TablePaginationOptions {
  currentPage?: number
  pageSize?: number
  total?: number
  pageSizes?: number[]
  layout?: string
}

export interface TableSelectionOptions {
  enabled?: boolean
  selectedKeys?: string[]
  key?: string
}

export interface TableSortOptions {
  prop?: string
  order?: 'ascending' | 'descending' | null
}

export interface TableColumn {
  label: string
  prop: string
  fixed?: boolean | 'left' | 'right'
  minWidth?: number | string
  width?: number | string
  align?: 'left' | 'center' | 'right'
  sortable?: boolean
  component?: string
  componentProps?: Record<string, any> | ((row: any) => Record<string, any>)
  componentEvents?: Record<string, (value: any, row: any) => Promise<boolean> | boolean>
  dictionary?: Record<string, string>
  format?: (row: any, value: any) => any
  searchable?: boolean
  required?: boolean
  placeholder?: string
  defaultValue?: any
  colSpan?: number
  options?: Array<{ label: string; value: any }>
  optionsPath?: string
  customRender?: boolean
}

export interface UseTableOptions<T = any> {
  data?: T[]
  remote?: boolean
  loading?: boolean
  page?: number
  pageSize?: number
  total?: number
  pageSizes?: number[]
  layout?: string
  columns?: TableColumn[]
  selectedRowKeys?: string[]
  rowKey?: string
  sortConfig?: TableSortOptions
  showOperation?: boolean
}

/**
 * 表格逻辑处理Hook
 */
export function useTable<T = any>(options: UseTableOptions<T> = {}) {
  // 基础状态
  const state = reactive({
    // 数据相关
    data: options.data || [],
    loading: options.loading || false,
    error: null as Error | null,

    // 分页相关
    pagination: {
      currentPage: options.page || 1,
      pageSize: options.pageSize || 10,
      total: options.total || 0,
      pageSizes: options.pageSizes || [10, 20, 50, 100],
      layout: options.layout || 'total, sizes, prev, pager, next, jumper',
    },

    // 选择相关
    selection: {
      selectedRowKeys: options.selectedRowKeys || [],
      selectedRows: [] as any[],
    },

    // 排序相关
    sort: {
      prop: options.sortConfig?.prop || '',
      order: options.sortConfig?.order || null,
    },

    // 列配置
    columns: options.columns || [],

    // 其他配置
    rowKey: options.rowKey || 'id',
    remote: options.remote || false,
  })

  // 表格引用
  const tableRef = ref<any>(null)

  // 计算属性
  const computedState = {
    // 显示的列
    visibleColumns: computed(() => state.columns.filter((col) => !col.component || col.component !== 'hidden')),

    // 查询列
    searchableColumns: computed(() => state.columns.filter((col) => col.searchable)),

    // 当前页数据
    currentPageData: computed(() => {
      if (state.remote) return state.data

      const { currentPage, pageSize } = state.pagination
      const start = (currentPage - 1) * pageSize
      const end = start + pageSize

      return state.data.slice(start, end)
    }),

    // 是否为空数据
    isEmpty: computed(() => state.data.length === 0),

    // 是否全选
    isAllSelected: computed(() => {
      if (state.data.length === 0) return false
      return state.selection.selectedRows.length === state.data.length
    }),

    // 是否有选中项
    hasSelected: computed(() => state.selection.selectedRows.length > 0),
  }

  // 方法
  const methods = {
    // 设置数据
    setData(data: T[]) {
      state.data = data as any
      state.pagination.total = data.length
    },

    // 设置加载状态
    setLoading(loading: boolean) {
      state.loading = loading
    },

    // 设置错误
    setError(error: Error | null) {
      state.error = error
    },

    // 设置页码
    setPage(page: number) {
      state.pagination.currentPage = page
    },

    // 设置每页条数
    setPageSize(pageSize: number) {
      state.pagination.pageSize = pageSize
      state.pagination.currentPage = 1 // 重置到第一页
    },

    // 设置总数
    setTotal(total: number) {
      state.pagination.total = total
    },

    // 设置选中行
    setSelectedRows(rows: T[]) {
      state.selection.selectedRows = rows as any
      state.selection.selectedRowKeys = rows.map((row: any) => row[state.rowKey])
    },

    // 设置排序
    setSort(prop: string, order: 'ascending' | 'descending' | null) {
      state.sort.prop = prop
      state.sort.order = order
    },

    // 刷新数据
    reload() {
      if (state.remote) {
        // 由外部处理刷新逻辑
        return {
          page: state.pagination.currentPage,
          pageSize: state.pagination.pageSize,
          sort: state.sort,
          timestamp: Date.now(),
        }
      } else {
        // 本地刷新处理
        return state.data
      }
    },

    // 清除选择
    clearSelection() {
      state.selection.selectedRows = []
      state.selection.selectedRowKeys = []
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
    },

    // 选择所有行
    selectAllRows() {
      if (tableRef.value) {
        tableRef.value.toggleAllSelection()
      }
    },

    // 处理某一行的选择状态
    toggleRowSelection(row: T, selected?: boolean) {
      if (tableRef.value) {
        tableRef.value.toggleRowSelection(row, selected)
      }
    },

    // 处理排序变化
    handleSortChange({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) {
      state.sort.prop = prop
      state.sort.order = order
      return methods.reload()
    },

    // 处理页码变化
    handlePageChange(page: number) {
      state.pagination.currentPage = page
      return methods.reload()
    },

    // 处理每页条数变化
    handleSizeChange(pageSize: number) {
      state.pagination.pageSize = pageSize
      state.pagination.currentPage = 1
      return methods.reload()
    },

    // 处理选择变化
    handleSelectionChange(selection: T[]) {
      state.selection.selectedRows = selection as any
      state.selection.selectedRowKeys = selection.map((row: any) => row[state.rowKey])
    },

    // 获取单元格值
    getCellValue(row: any, column: TableColumn) {
      const value = row[column.prop]
      if (column.format) {
        return column.format(row, value)
      }
      if (column.dictionary && value !== undefined && value !== null) {
        return column.dictionary[value] || value
      }
      return value === undefined || value === null ? '-' : value
    },

    // 处理单元格值更新
    async handleCellValueUpdate(value: any, row: any, column: TableColumn) {
      if (!column.componentEvents?.['update:modelValue']) return

      try {
        const result = await column.componentEvents['update:modelValue'](value, row)
        if (result) {
          ElMessage.success('更新成功')
          methods.reload()
        }
      } catch (error) {
        ElMessage.error('更新失败')
        console.error('单元格更新失败:', error)
      }
    },

    // 获取组件属性
    getComponentProps(column: TableColumn, row: any) {
      if (!column.componentProps) return {}
      return typeof column.componentProps === 'function' ? column.componentProps(row) : column.componentProps
    },
  }

  // 返回状态和方法
  return {
    // 暴露状态
    ...toRefs(state),
    ...computedState,

    // 暴露方法
    ...methods,

    // 暴露引用
    tableRef,
  }
}
